package com.kzw.web;

import java.io.IOException;

import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;

import my.mvc.Annotation.JSONOutput;
import my.mvc.RequestContext;
import my.util.ResponseUtils;

import com.kzw.bean.Record;
import com.kzw.dao.support.Page;
import com.kzw.entity.Article;
import com.kzw.entity.Dictionary;
import com.kzw.json.Jackson;
import com.kzw.service.ArticleService;

public class ArticleAction {
	
	private ArticleService articleService = new ArticleService();

	/**
	 * 增加或修改
	 * */
	public void save(RequestContext rc) throws ServletException, IOException {
		// 将请求参数自动包装成Bean对象
		Article article = rc.form(Article.class);
		
		if(article.getId()==null || article.getId()==0) {
			// 增加
			articleService.add(article);
		} else {
			// 修改
			articleService.update(article);
		}
		
		// 输出JSON
		String json = Jackson.me().toJson(new Record(true));
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 列表
	 * */
	public void list(RequestContext rc) throws ServletException, IOException {
		int pageNo = rc.param("page", 1);
		int pageSize = rc.param("limit", 15);
		String orderBy = rc.param("orderBy", "");
		String orderDir = rc.param("orderDir", "");
		
		Page<Article> page = new Page<>(pageNo, pageSize);
		if(StringUtils.isNotBlank(orderBy)) {
			page.setOrderBy(orderBy);
			page.setOrder(orderDir);
		}
		
		Record record = articleService.findPage(page);
		// 输出JSON
		String json = Jackson.me().without(Article.class, "content")
						.with(Dictionary.class, "itemValue").toJson(record);
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 删除
	 * */
	public void del(RequestContext rc) throws ServletException, IOException {
		long id = rc.param("id", 0L);
		articleService.remove(id);
		
		// 返回JSON
		String json = Jackson.me().toJson(new Record(true));
		ResponseUtils.renderJson(rc.response(), json);
	}
	
	/**
	 * 修改之前，获得信息，用于回显
	 * */
	public void get(RequestContext rc) throws ServletException, IOException {
		String id = rc.param("id");
		if(id!=null && !id.equals("")) {
			Article article = articleService.findById(Long.parseLong(id));
			rc.reqAttr("article", article);
			rc.forward("/pages/article_form.jsp");
		}
	}
	
	/**
	 * 批量删除
	 * */
	@JSONOutput
	public Record multiDel(RequestContext rc) throws ServletException, IOException {
		String ids = rc.param("ids");
		if(StringUtils.isNotBlank(ids)) {
			articleService.multiDel(ids);
		}		
		return new Record(true);
	}
	
	/**
	 * 查看文章
	 * */
	public void view(RequestContext rc) throws ServletException, IOException {
		Long id = rc.param("id", 0L);
		Article article = articleService.findById(id);
		rc.reqAttr("article", article);
		rc.forward("/pages/details.jsp");
	}

}
